'use strict';

const { Service } = require('egg');
const Result = require('../util/result');

class TrainService extends Service {

  async index(query) {
    const info = await this.ctx.model.Train.findAll(query);
    return Result.success(info);
  }

  async create(data) {
    const info = await this.ctx.model.Train.create({ ...data });
    if (!info) return Result.fail();
    return Result.success(info);
  }

  async show(id) {
    const info = await this.findByPk(id);
    if (!info) return Result.fail();
    return Result.success(info);
  }

  async update(id, data) {
    const info = await this.findByPk(id);
    if (!info) return Result.warn(-1, 'not fonud');
    const res = await this.ctx.model.Train.update({ ...data }, {
      where: {
        id,
      },
    });
    if (res[0] <= 0) return Result.warn(-1, '更新失败,请重试');
    const updated = await this.findByPk(id);
    return Result.success(updated);
  }

  async destroy(id) {
    const info = await this.findByPk(id);
    if (!info) return Result.warn(-1, 'id不存在');
    const res = await this.ctx.model.Train.destroy({
      where: {
        id,
      },
    });

    if (res[0] <= 0) return Result.fail();
    return Result.noDataSuccess();
  }

  async findByPk(id) {
    return await this.ctx.model.Train.findByPk(id);
  }

  async findByTrainNum(train_num) {
    const info = await this.ctx.model.Train.findOne({
      where: { train_num },
    });
    return info;
  }
}

module.exports = TrainService;
